package cn.huimin.httpClient.impl;

import cn.huimin.httpClient.AbstractHttpClient;
import cn.huimin.httpClient.IHttpClient;
import cn.huimin.httpClient.ex.URLEmptyException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Martin on 2017-2-27.
 */
public class HMPutRequest extends AbstractHttpClient{

    private static Log logger = LogFactory.getLog(HMPutRequest.class);

    public HMPutRequest() {
    }

    public static IHttpClient getInstance(){
        return new HMPutRequest();
    }

    @Override
    public RequestMethod getMethodType() {
        return RequestMethod.PUT;
    }

    @Override
    public String sendData() throws URLEmptyException {

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建httpPut
        HttpPut httpPut = new HttpPut(client.getPostUrl().toString());
        httpPut.addHeader("Content-Type", "application/json;charset=UTF-8");

        //设置请求头
        if (client.getHeader() != null && client.getHeader().size() > 0) {
            Map<String, String> map = client.getHeader();
            for (String key : map.keySet()) {
                httpPut.setHeader(key, map.get(key));
            }
        }
        // 创建参数队列
        JSONObject jsonObject = new JSONObject();

        for (Map.Entry<String, Object> entry : client.getParams().entrySet()) {
            if (entry.getValue() instanceof String) {
                jsonObject.put(entry.getKey(),entry.getValue());
            }
        }

        // 执行post请求.
        CloseableHttpResponse response = null;
        try {
            StringEntity jsonEntity = new StringEntity(jsonObject.toJSONString(),"UTF-8");

            httpPut.setEntity(jsonEntity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
            httpPut.setConfig(requestConfig);

            logger.info("Executing Request  - HttpPut start");
            logger.info("Executing Request " + httpPut.getURI());
            logger.info("Executing Request " + EntityUtils.toString(httpPut.getEntity()));
            response = httpclient.execute(httpPut);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseStatus = response.getStatusLine().getStatusCode() + "";
                logger.info("Response Status: " + responseStatus);
                responseData = EntityUtils.toString(entity, encoding);
                logger.info("Response Content: " + responseData);
                logger.info("--------------------------------------------- end");
            }
            logger.info("Executing Request  - HttpPut end");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(response!= null)
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return responseData;
    }
}
